package com.quectel.core.module.partybuildingsurvey.impl;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.fasterxml.jackson.core.type.TypeReference;
import com.quectel.constant.core.partybuilding.PartySurveyConstants;
import com.quectel.constant.global.SystemConstants;
import com.quectel.core.constants.RedisCacheConstants;
import com.quectel.core.module.partybuildingsurvey.dao.PartySurveyPersonAnswerDao;
import com.quectel.core.module.partybuildingsurvey.dto.PartySurveyDto;
import com.quectel.core.module.partybuildingsurvey.dto.PartySurveyPersonAnswerDto;
import com.quectel.core.module.partybuildingsurvey.dto.PartySurveyPersonRecordDto;
import com.quectel.core.module.partybuildingsurvey.dto.PartySurveyQuestionDto;
import com.quectel.core.module.partybuildingsurvey.entity.PartySurveyPersonAnswerEntity;
import com.quectel.core.module.partybuildingsurvey.service.PartySurveyPersonAnswerService;
import com.quectel.core.module.partybuildingsurvey.service.PartySurveyPersonRecordService;
import com.quectel.core.module.partybuildingsurvey.service.PartySurveyQuestionService;
import com.quectel.core.module.partybuildingsurvey.service.PartySurveyService;
import com.quectel.util.common.CopyUtils;
import com.quectel.util.common.JacksonUtils;
import com.quectel.util.kit.CacheKit;
import com.quectel.util.kit.Snowflake;
import com.quectel.util.mybatis.MyBatisPlusUtils;
import org.apache.dubbo.config.annotation.DubboService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;

import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.function.Consumer;
import java.util.function.Function;
import java.util.stream.Collectors;

/**
 * @author bob
 * @email bob.yu@quectel.com
 * @date 2023/05/24 11:38
 */
@DubboService
public class PartySurveyPersonAnswerServiceImpl implements PartySurveyPersonAnswerService {

    private static final Logger LOGGER = LoggerFactory.getLogger(PartySurveyPersonAnswerServiceImpl.class);

    /**
     * 入参解释:实体id
     */
    private static final Function<Long, String> PARTY_SURVEY_PERSON_ANSWER_CACHE_BY_ID_FUNC = id -> String.format(RedisCacheConstants.PROJECT_NAME + "PARTY_SURVEY_PERSON_ANSWER_CACHE_BY_ID:%d", id);

    /**
     * 清除缓存方法
     */
    private static final Consumer<PartySurveyPersonAnswerDto> CLEAR_CACHE_FUNC = dto -> {
        CacheKit.invalidRedisCache(PARTY_SURVEY_PERSON_ANSWER_CACHE_BY_ID_FUNC.apply(dto.getId()));
    };

    @Autowired
    private PartySurveyPersonAnswerDao partySurveyPersonAnswerDao;
    @Autowired
    private PartySurveyPersonRecordService partySurveyPersonRecordService;
    @Autowired
    private PartySurveyService partySurveyService;
    @Autowired
    private PartySurveyQuestionService partySurveyQuestionService;


    @Override
    public List<PartySurveyPersonAnswerDto> selectBySurveyIdAndQuestionId(Long surveyId, Long questionId) {
        List<PartySurveyPersonAnswerEntity> list = partySurveyPersonAnswerDao.selectList(new LambdaQueryWrapper<PartySurveyPersonAnswerEntity>()
                .eq(PartySurveyPersonAnswerEntity::getPartySurveyId, surveyId)
                .eq(PartySurveyPersonAnswerEntity::getQuestionId, questionId));
        List<PartySurveyPersonAnswerDto> result =  CopyUtils.copyList(list,PartySurveyPersonAnswerDto.class);
        result.forEach(this::paddingField);
        return result;
    }
    @Override
    public List<PartySurveyPersonAnswerDto> selectByRecordId(Long recordId) {

        PartySurveyPersonRecordDto partySurveyPersonRecordDto = partySurveyPersonRecordService.selectCacheById(recordId);
        if(partySurveyPersonRecordDto ==null){
            return Collections.emptyList();
        }
        //根据题目排序
        PartySurveyDto partySurveyDto = partySurveyService.selectCacheById(partySurveyPersonRecordDto.getPartySurveyId());
        if(partySurveyDto ==null){
            return Collections.emptyList();
        }
        List<PartySurveyQuestionDto> bindQuestion = partySurveyDto.getBindQuestion();
        Map<Long, PartySurveyQuestionDto> collect = bindQuestion.stream().collect(Collectors.toMap(PartySurveyQuestionDto::getId, Function.identity(), (key1, key2) -> key2));

        List<PartySurveyPersonAnswerEntity> list = partySurveyPersonAnswerDao.selectList(new LambdaQueryWrapper<PartySurveyPersonAnswerEntity>()
                .eq(PartySurveyPersonAnswerEntity::getRecordId, recordId));
        List<PartySurveyPersonAnswerDto> result = CopyUtils.copyList(list, PartySurveyPersonAnswerDto.class);
        result.forEach(partySurveyPersonAnswerDto -> {
            PartySurveyQuestionDto partySurveyQuestionDto = collect.get(partySurveyPersonAnswerDto.getQuestionId());
            if(partySurveyQuestionDto!=null){
                handleAnswerData(partySurveyQuestionDto,partySurveyPersonAnswerDto);
            }
        });


        return result.stream().sorted((o1, o2) -> {
            PartySurveyQuestionDto sort1 = collect.get(o1.getQuestionId());
            PartySurveyQuestionDto sort2 = collect.get(o1.getQuestionId());
            if (sort1 != null && sort2 != null) {
                return sort1.getSort() - sort2.getSort();
            } else {
                return Math.toIntExact((o1.getId() - o2.getId()));
            }
        }).collect(Collectors.toList());
    }

    @Override
    public void deleteByRecordId(Long surveyId) {
        partySurveyPersonAnswerDao.delete(new LambdaQueryWrapper<PartySurveyPersonAnswerEntity>()
                .eq(PartySurveyPersonAnswerEntity::getRecordId, surveyId)
        );
    }


    @Override
    public PartySurveyPersonAnswerDto selectCacheById(Long id) {
        return CacheKit.cacheToRedis(
                () -> selectById(id),
                PARTY_SURVEY_PERSON_ANSWER_CACHE_BY_ID_FUNC.apply(id),
                SystemConstants.NOT_NULL_CACHE_EXPIRE_SECONDS
        );
    }

    @Override
    public PartySurveyPersonAnswerDto selectById(Long id) {
        PartySurveyPersonAnswerEntity entity = partySurveyPersonAnswerDao.selectById(id);
        return paddingField(CopyUtils.copyObj(entity, PartySurveyPersonAnswerDto.class));
    }

    @Override
    public List<PartySurveyPersonAnswerDto> queryList(Map<String, Object> params) {
        List<PartySurveyPersonAnswerEntity> list = partySurveyPersonAnswerDao.queryList(params);
        List<PartySurveyPersonAnswerDto> result = CopyUtils.copyList(list, PartySurveyPersonAnswerDto.class);
        result.forEach(this::paddingField);
        return result;
    }

    /**
     * 此方法慎用 禁止填充List一类 比如一个人有多个地址这里不允许填充
     * 填充的原则是: 1:被填充对象不经常变换 2:根据id可以走缓存 3数据足够简单 比如设备类型 所属园区等
     *
     * @param dto
     * @return
     */
    private PartySurveyPersonAnswerDto paddingField(PartySurveyPersonAnswerDto dto){
        if (dto != null){
            PartySurveyQuestionDto partySurveyQuestionDto = partySurveyQuestionService.selectCacheByIdNoPadding(dto.getQuestionId());
            handleAnswerData(partySurveyQuestionDto,dto);
        }
        return dto;
    }
    private PartySurveyPersonAnswerDto handleAnswerData(PartySurveyQuestionDto partySurveyQuestionDto ,PartySurveyPersonAnswerDto dto){
        if(PartySurveyConstants.QuestionType.SINGLE_CHOICE.getType().equals(partySurveyQuestionDto.getType())
                ||PartySurveyConstants.QuestionType.MULTIPLE_CHOICE.getType().equals(partySurveyQuestionDto.getType())
                ||PartySurveyConstants.QuestionType.PIC_SINGLE_CHOICE.getType().equals(partySurveyQuestionDto.getType())
                ||PartySurveyConstants.QuestionType.PIC_MULTIPLE_CHOICE.getType().equals(partySurveyQuestionDto.getType())
        ){
            dto.setChoiceAnswer(JacksonUtils.parseArray(dto.getContent(),Long.class));
        }
        if(PartySurveyConstants.QuestionType.BLANK.getType().equals(partySurveyQuestionDto.getType())
        ){
            dto.setBlankAnswer(JacksonUtils.parse(dto.getContent(),  new TypeReference<Map<Long,String>>() {}));
        }
        if(PartySurveyConstants.QuestionType.EVALUATE.getType().equals(partySurveyQuestionDto.getType())
        ){
            dto.setEvaluateAnswer(JacksonUtils.parse(dto.getContent(),  new TypeReference<Map<Long,Double>>() {}));
        }
        return dto;
    }


    @Override
    public int queryTotal(Map<String, Object> params) {
        return partySurveyPersonAnswerDao.queryTotal(params);
    }

    @Override
    public Long save(PartySurveyPersonAnswerDto dto) {
        PartySurveyPersonAnswerEntity entity = CopyUtils.copyObj(dto, PartySurveyPersonAnswerEntity.class);
        entity.setId(Snowflake.nextId());
        partySurveyPersonAnswerDao.insert(entity);
        return entity.getId();
    }

    @Override
    public void updateById(PartySurveyPersonAnswerDto dto) {
        PartySurveyPersonAnswerEntity entity = CopyUtils.copyObj(dto, PartySurveyPersonAnswerEntity.class);

        partySurveyPersonAnswerDao.updateById(entity);

        CLEAR_CACHE_FUNC.accept(dto);
    }

    @Override
    public void updateAllColumnById(PartySurveyPersonAnswerDto dto) {
        PartySurveyPersonAnswerEntity entity = CopyUtils.copyObj(dto, PartySurveyPersonAnswerEntity.class);

        MyBatisPlusUtils.updateAllColumnById(entity, partySurveyPersonAnswerDao);

        CLEAR_CACHE_FUNC.accept(dto);
    }

    @Override
    public void deleteById(Long id) {

        CLEAR_CACHE_FUNC.accept(selectById(id));

        partySurveyPersonAnswerDao.deleteById(id);

    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void deleteBatch(Long[] ids) {
        for (Long id : ids) {
            deleteById(id);
        }
    }
}
